# -*- coding: utf-8 -*-
import base64
import hashlib
import json
import random
import urllib
from collections import OrderedDict

import requests
import xmltodict
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

# _GATEWAY = 'http://open.288kq.com/gateway/soa'
# _GATEWAY = 'http://api.mxc88.com/gateway/soa'
# _QUERY_GATEWAY = 'http://api.mxc88.com/gateway/paystatus'
# _GATEWAY = 'http://open.1899v.com/gateway/soa'
_GATEWAY = 'http://api.cws8.com/gateway/soa'
# _GATEWAY = 'http://118.212.233.158/gateway/soa'
# _GATEWAY = 'http://158.233.212.118./gateway/soa'
_QUERY_GATEWAY = 'http://api.cws8.com/gateway/paystatus'
# witch
APP_CONF = {
    '1054': {
        'API_KEY': 'c1373f19e6eca25e37fe341805e3248d',
    },
    '1039': {
        'API_KEY': '5c12643cbd5ca013261355ab3b2e349c',
    },
    '1056': {
        'API_KEY': 'cf50ceea90bb2f784f63e2b686ec9c9d',
    },
    '2161': {
        'API_KEY': 'ef912e33acf888c615702431dcd1cfe3',
    },
    '2162': {
        'API_KEY': 'fe73d10c006f59884550272a8ff8ca78',
    },
    '2163': {
        'API_KEY': '1d675e9c1563d7cd6959f77fa6459221',
    },
    '2234': {  # witch 支付宝 10-5000
        'API_KEY': '3ca9fe7cd57f00558a48401fa243580e',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


# QQ扫码	010000
# 微信扫码	010001
# 支付宝扫码	010002
# 微信APP	010004
# 支付宝APP	010005

# 微信支付	010007
# 支付宝支付	010008
# 微信公众号	010009
# 银联支付	010010
# 京东扫码	010011
# 支付宝免密app	010012
# PC银联	010013
# 京东钱包	010014
def _get_pay_type(service):
    if service == 'alipay':
        return '010008'
    elif service == 'alipay_scan':
        return '010002'
    elif service == 'wxpay':
        return '010007'
    elif service == 'union':
        return '010010'
    elif service == 'qq':
        return '010006'
    else:
        return '010014'  # jd


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("tonglepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '58.64.187.23'


def get_phone_type(info):
    if 'android' in info.get('sdk_version', ''):
        return 'AND_WAP'
    else:
        return 'iOS_WAP'


def dict_to_xml_str(tag, d):
    parts = ['<{}>'.format(tag)]
    for key, val in d.items():
        parts.append('<{0}>{1}</{0}>'.format(key, val))
        # parts.append('<{0}>![CDATA[{1}]]</{0}>'.format(key, val))
    parts.append('</{}>'.format(tag))
    return ''.join(parts)


def _fix_pay_amount(pay, pay_amount):
    extend = json.loads(pay.extend or '{}')
    if pay_amount >= 10 and int(pay_amount) == pay_amount:
        discount = random.randint(1, 10)
        pay_amount = pay_amount - float(discount) / 100
        extend.update({'discount': str(float(discount) / 100)})
        order_db.fill_extend(pay.id, extend)
    return pay_amount


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')

    biz_dict = OrderedDict((
        ('mch_app_id', "https://www.baidu.com",),
        ('device_info', get_phone_type(info)),
        ('ua',
         "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"),
        ('mch_app_name', 'test'),
        ("cashier_desk", "0"),
    ))
    _LOGGER.info("tonglepay create  biz_dict: %s", json.dumps(biz_dict))
    encoded_data = urllib.quote(json.dumps(biz_dict))
    b_data = base64.b64encode(encoded_data)
    parameter_dict = OrderedDict((
        ('version', '1.0'),
        ('charset', 'UTF-8'),
        ('merchant_id', app_id),
        ('out_trade_no', str(pay.id)),
        ('trade_type', _get_pay_type(service)),
        ('user_ip', _get_device_ip(info)),
        ('subject', 'charge'),
        ('body', 'charge_body'),
        ('user_id', str(pay.id)[-6:]),
        ('total_fee', '%.2f' % pay_amount),
        ('notify_url', '{}/pay/api/{}/tonglepay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('return_url', '{}/pay/api/{}/tonglepay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('nonce_str', '213123321312'),
        ('biz_content', b_data),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("tonglepay create  data: %s", json.dumps(parameter_dict))
    xml = dict_to_xml_str('xml', parameter_dict)
    _LOGGER.info("tonglepay create  xml: %s, %s", xml, _GATEWAY)
    headers = {'Content-Type': 'application/xml;charset=utf-8'}
    # response = requests.post(_GATEWAY, data=xml, timeout=5, verify=False)
    response = requests.post(_GATEWAY, data=xml, headers=headers, timeout=5, verify=False)
    # response = requests.post(_GATEWAY, data=xml, headers=headers, timeout=5)
    _LOGGER.info("tonglepay create  rsp data: %s", response.text)
    data = xmltodict.parse(response.text)['xml']
    return {'charge_info': data['pay_info']}


# SUCCESS
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("tonglepay notify data: %s", data)
    _LOGGER.info("tonglepay notify body: %s", request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('tonglepay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['trade_status']
    trade_no = data['trade_no']
    total_fee = float(data['total_fee'])
    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    # 1.表示成功
    # 2.表示失败
    # 4.表示交易中
    if trade_status == '1':
        _LOGGER.info('tonglepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchant_id', app_id),
        ('out_trade_no', str(pay_id)),
        ('version', '1.0'),
        ('charset', 'UTF-8'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("tonglepay query  data: %s", parameter_dict)
    xml = dict_to_xml_str('xml', parameter_dict)
    headers = {'Content-Type': 'application/xml;charset=utf-8'}
    response = requests.post(_QUERY_GATEWAY, data=xml, headers=headers, timeout=5, verify=False)
    _LOGGER.info("tonglepay query  rsp data: %s", response.text)
    if response.status_code == 200:
        data = xmltodict.parse(response.text)['xml']
        trade_status = str(data['result_code'])
        trade_no = data['trade_no']
        total_fee = float(data['total_fee'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 1.表示成功
        # 2.表示失败
        # 4.表示交易中
        if trade_status == '1':
            _LOGGER.info('tonglepay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('tonglepay data error, status_code: %s', response.status_code)
